package com.campsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campsys.domain.LoginUser;
import com.campsys.domain.TSysUser;
import com.campsys.mapper.UserMapper;
import com.campsys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<TSysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(TSysUser::getLoginName,username);

        TSysUser user = userService.getOne(qw);
        if (user == null){

            throw new RuntimeException("账号不存在");

        }
        
        if(!user.getStatus().equals("1")){

            throw new RuntimeException("账号异常，已被删除");

        }

        //获取权限信息
        List<String> permissions = userMapper.getPermissionsByUserId(user.getId());


        LoginUser loginUser = new LoginUser();
        loginUser.setTSysUser(user);
        loginUser.setPermissions(permissions);


        return loginUser;
    }
}
